﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Collections;
using BrightIdeasSoftware;


namespace Windows_Phone_App_Dashboard
{
    public partial class frmDashboard : Form
    {
        List<UserRating> ratingsList = new List<UserRating>(); 
        List<Marketplace> marketplacesList = new List<Marketplace>();
        List<WPApplication> appsList = new List<WPApplication>();

        public frmDashboard()
        {
            InitializeComponent();
        }

        private void GetRatings(string reviewUrl, string marketplace)
        {
            //Get ratings for app based on marketplace
            try
            {
                string ZuneURL = "http://catalog.zune.net/v3.2/";
                reviewUrl = ZuneURL + marketplace + "/" +  reviewUrl;
                var xmlDoc = new XmlDocument();
                xmlDoc.Load(reviewUrl);
                XmlNodeList nodelist;
                XmlNodeList linklist;
                XmlNamespaceManager nameSpaceManager = new XmlNamespaceManager(xmlDoc.NameTable);
                nameSpaceManager.AddNamespace("a", "http://www.w3.org/2005/Atom");
                linklist = xmlDoc.SelectNodes("/a:feed/a:link",nameSpaceManager);
                foreach (XmlNode linkNode in linklist)
                {
                    string nextUrl = null;

                    if (linkNode.Attributes["rel"].Value == "next")
                    {
                        nextUrl = linkNode.Attributes["href"].Value;
                        if (nextUrl != null)
                        {
                            nodelist = xmlDoc.SelectNodes("/a:feed/a:entry", nameSpaceManager);
                            foreach (XmlNode node in nodelist)
                            {
                                UserRating currentRating = new UserRating();
                                currentRating.rating = Convert.ToInt16(node.LastChild.InnerText);
                                XmlNode author = node.SelectSingleNode("a:author", nameSpaceManager);
                                currentRating.author = author.InnerText;
                                XmlNode content = node.SelectSingleNode("a:content", nameSpaceManager);
                                currentRating.content = content.InnerText;
                                currentRating.marketplace = marketplace;
                                ratingsList.Add(currentRating);
                            }
                            nextUrl = nextUrl.Replace("/v3.2/" + marketplace + "/", "");
                            //If next url is not empty, get ratings using the "next" url
                            GetRatings(nextUrl, marketplace);
                        }
                    }
                }

            }
            catch (Exception)
            {

               //Ignore error (for now) and proceed with next url or marketplace
            }

        }
       

        private void LoadMarketplaces()
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load("Marketplaces.xml");
            XmlNodeList marketplacesNodeList = xmlDoc.SelectNodes("marketplaces/marketplace");
            foreach (XmlNode node in marketplacesNodeList)
            {
                //Add items to  Marketplace list
                Marketplace place = new Marketplace();
                place.language = node.SelectSingleNode("language").InnerText;
                place.marketplace = node.SelectSingleNode("title").InnerText;
                marketplacesList.Add(place);
            }

            lstviewMarketplace.SetObjects(marketplacesList);

        }
        private void Form1_Load(object sender, EventArgs e)
        {
            LoadApps();
            LoadMarketplaces();
        }

        public void LoadApps()
        {  //Load all appss from Apps.xml file
            try
            {
                appsList.Clear();
                cmbAppsList.DataSource = null;
                cmbAppsList.Items.Clear();
                WPApplication wpApp = new WPApplication();
                wpApp.appID = "Select Application";
                wpApp.appTitle = "Select Application";
                appsList.Add(wpApp);
                XmlDocument doc = new XmlDocument();
                doc.Load("Apps.xml");
                XmlNodeList appList = doc.SelectNodes("apps/app");

                foreach (XmlNode app in appList)
                {
                    wpApp = new WPApplication();
                    wpApp.appID = app.Attributes["appid"].Value.ToString();
                    wpApp.appTitle = app.Attributes["appname"].Value.ToString();
                    wpApp.appDescription = app.Attributes["description"].Value.ToString();
                    wpApp.appImageURL = app.Attributes["image"].Value.ToString();
                    appsList.Add(wpApp);
                }
                cmbAppsList.DataSource = appsList;
                cmbAppsList.DisplayMember = "appTitle";
                cmbAppsList.ValueMember = "appId";
                cmbAppsList.SelectedIndex = 0;
                cmbAppsList.Refresh();
                
            }
            catch (Exception ex)
            {

                MessageBox.Show("Error loading apps. Please try again. Error : " + ex.Message);
            }
        
        }

        
        private void GetAverageRating(int ratingCount, int ratingSum)
        {
            try
            {
                //Get average rating for each marketplace
                pictureAverageRating.Visible = true;
                lblAverageRating.Visible = true;
                pictureAverageRating.Image = null;
                if (ratingSum > 0)
                {
                    //display a-5 star based on average rating
                    int averageRating = ratingSum / ratingCount;
                    if (averageRating == 1 || averageRating == 2)
                    {
                        pictureAverageRating.Image = Properties.Resources._1star;
                    }
                    if (averageRating == 3 || averageRating == 4)
                    {
                        pictureAverageRating.Image = Properties.Resources._2star;
                    }
                    if (averageRating == 5 || averageRating == 6)
                    {
                        pictureAverageRating.Image = Properties.Resources._3star;
                    }
                    if (averageRating == 7 || averageRating == 8)
                    {
                        pictureAverageRating.Image = Properties.Resources._4star;
                    }
                    if (averageRating == 9 || averageRating == 10)
                    {
                        pictureAverageRating.Image = Properties.Resources._5star;
                    }
                }
                else
                {
                    pictureAverageRating.Visible = false;
                    lblAverageRating.Visible = false;
                    pictureAverageRating.Image = null;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("There was an error calculating average rating. Please try again. Error: " + ex.Message);
            }

        }


        private void lstviewMarketplace_SelectionChanged(object sender, EventArgs e)
        {
            if (lstviewMarketplace.SelectedItem != null)
            {
                if (cmbAppsList.SelectedValue.ToString() != "Select Application")
                {
                    Marketplace m = (Marketplace)lstviewMarketplace.SelectedItem.RowObject;
                    if (lstviewMarketplace.SelectedIndex != 0)
                    {
                        List<UserRating> currentRatings = ratingsList.FindAll(item => item.marketplace == m.language);
                        pictureAverageRating.Image = null;

                        //lstviewReviews.Items.Clear();
                        lstviewReviews.SetObjects(currentRatings);
                        pictureAverageRating.Visible = false;
                        lblAverageRating.Visible = false;
                        int ratingsSum = currentRatings.Sum(item => item.rating);
                        GetAverageRating(currentRatings.Count, ratingsSum);
                    }
                    else
                    {
                        //lstviewReviews.Items.Clear();
                        lstviewReviews.SetObjects(ratingsList);
                        int ratingsSum = ratingsList.Sum(item => item.rating);
                        GetAverageRating(ratingsList.Count, ratingsSum);

                    }
                }
            }

        }

      
        private void ratingsWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                ratingsList.Clear();
                //Open each marketplace and get ratings for the selected app
                for (int i = 0; i < marketplacesList.Count; i++)
                {
                    ratingsWorker.ReportProgress((i + 1) * 100 / (marketplacesList.Count));
                    string selectedAppID = "";
                    if (cmbAppsList.InvokeRequired)
                    {
                        cmbAppsList.Invoke(new MethodInvoker(delegate
                        {
                            selectedAppID = cmbAppsList.SelectedValue.ToString();
                        }));

                    }
                    GetRatings("apps/" + selectedAppID + "/reviews", marketplacesList[i].language);
                }
                if (lstviewMarketplace.InvokeRequired)
                {
                    lstviewMarketplace.Invoke(new MethodInvoker(delegate { lstviewMarketplace.SelectedIndex = 0; }));
                }


                //Load Images fort Rating
                ImageList lst = new ImageList();
                lst.Images.Add(Properties.Resources.star);
                RatingRenderer.ImageList = lst;
                lstviewReviews.SetObjects(ratingsList);
                //lstviewReviews.Refresh();
            }
            catch (Exception)
            {
                
                
            }
            

        }

        private void ratingsWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar.Visible = true;
            progressBar.Value = e.ProgressPercentage;

        }

        private void ratingsWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            progressBar.Visible = false;
            progressBar.Value = 0;
            cmbAppsList.Enabled = true;
            btnRefresh.Enabled = true;
            btnAppRefresh.Enabled = true;
            pictureAverageRating.Visible = true;
            lblAverageRating.Visible = true;
            
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            if (cmbAppsList.SelectedItem != null)
            {
                if (cmbAppsList.SelectedValue.ToString() != "Select Application")
                {
                    if (!ratingsWorker.IsBusy)
                    {
                        ratingsWorker.RunWorkerAsync();
                        WPApplication p = (WPApplication)cmbAppsList.SelectedItem;
                        richTextDescription.Text = p.appDescription;
                        pictureAppImage.ImageLocation = p.appImageURL;
                        cmbAppsList.Enabled = false;
                        btnRefresh.Enabled = false;
                        btnAppRefresh.Enabled = false;
                        pictureAverageRating.Visible = false;
                        lblAverageRating.Visible = false;
                    }


                }
            }
        }

        private void cmbAppsList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbAppsList.SelectedItem != null)
            {
                if (cmbAppsList.SelectedValue.ToString() != "Select Application")
                {
                    if (!ratingsWorker.IsBusy)
                    {
                        lstviewReviews.Items.Clear();
                        ratingsWorker.RunWorkerAsync();
                        WPApplication p = (WPApplication)cmbAppsList.SelectedItem;
                        richTextDescription.Text = p.appDescription;
                        pictureAppImage.ImageLocation = p.appImageURL;
                        cmbAppsList.Enabled = false;
                        btnRefresh.Enabled = false;
                        btnAppRefresh.Enabled = false;
                        pictureAverageRating.Visible = false;
                        lblAverageRating.Visible = false;
                    }
                    
                    
                }
            }
        }

        private void manageApplicationsToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            frmAdd add = new frmAdd();
            add.ShowDialog();
        }

        private void lstviewReviews_HyperlinkClicked(object sender, HyperlinkClickedEventArgs e)
        {

            System.Diagnostics.Process.Start("http://social.zune.net/my/sendmessage.aspx?recipients=" + e.Url + "&type=Message");
           
        }

        private void removeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmAppList add = new frmAppList();
            add.ShowDialog();
        }

        private void btnAppRefresh_Click(object sender, EventArgs e)
        {
            cmbAppsList.SelectedIndex = 0;
            LoadApps();
        }

        

        
    }
}
